<script setup lang="ts">
import Session from '@core/engine/Session';
import Console, { ParentRegion, Region } from '@core/engine/Console';
import HistoryHelper from '@core/utils/HistoryHelper';
import SubAppHelper from '@main/utils/SubAppHelper';
import IconCaretUp from '@main/assets/caret.up.white.svg?component';
import IconCaretDown from '@main/assets/caret.down.gray.svg?component';
import IconArrowLeft from '@main/assets/arrow.left.gray.svg?component';
import IconLocation from '@main/assets/location.red.svg?component';
import { AppNames } from '@/subApps';

const { t } = useI18n({ inheritLocale: true, useScope: 'local' });

const currentSubApp = ref(SubAppHelper.getCurrentSubApp());

onBeforeRouteLeave((to) => {
  currentSubApp.value = SubAppHelper.getCurrentSubApp(to.name);
});
const subAppsNeedToHide = [AppNames.EShield];
const shouldShown = computed(() => {
  if (!currentSubApp.value) {
    return true;
  }
  return !subAppsNeedToHide.includes(currentSubApp.value);
});

const popperModifiers = [
  { name: 'offset', options: { offset: [206, 5] } },
];

const isExpanded = ref(false);
const onVisibleChange = (isVisible: boolean) => {
  isExpanded.value = isVisible;
};

const isShownRegionParents = ref(true);
const regionParentGroups = await Console.getPlatformPinyinGroups();
const remoteRegion = Session.getRegion();
const selectingRegionParent = reactive({} as ParentRegion);
const onClickRegionParent = (regionParent: ParentRegion) => {
  Object.assign(selectingRegionParent, regionParent);
  isShownRegionParents.value = false;
};
const onClickBack = () => {
  isShownRegionParents.value = true;
};
const isSwitchingRegion = ref(false);
const onClickRegion = async (region: Region) => {
  const isPartnershipRegion = !region.uuid;
  if (isPartnershipRegion) {
    HistoryHelper.openNewTab(region.zoneUrl);
    return;
  }
  isSwitchingRegion.value = true;
  try {
    await Session.setRegion(region);
  } finally {
    isSwitchingRegion.value = false;
  }
};
</script>

<template>
  <ElDropdown
    v-if="shouldShown"
    class="region-selector"
    popper-class="region-popper"
    :popper-options="{ modifiers: popperModifiers }"
    trigger="click"
    @visible-change="onVisibleChange"
  >
    <div v-loading="isSwitchingRegion" class="selected-region" :class="{ active: isExpanded }">
      <div class="content">
        <IconLocation class="icon-location" />
        <span>{{remoteRegion?.zoneName}}</span>
      </div>
      <IconCaretDown v-if="isExpanded" class="icon-arrow"/>
      <IconCaretUp v-else class="icon-arrow" />
    </div>
    <template #dropdown>
      <div
        v-loading="isSwitchingRegion"
        :element-loading-text="t('regionSwitching')"
        element-loading-svg-view-box=""
        class="regions-container"
      >
        <div v-if="isShownRegionParents" class="region-groups">
          <div v-for="group in regionParentGroups" :key="group.pinyinRange" class="pinyin-row">
            <div class="pinyin-range">{{group.pinyinRange}}</div>
            <div class="region-parents">
              <ElButton
                v-for="regionParent in group.platformParents"
                :key="regionParent.parentName"
                text
                color="#353f58"
                class="region-parent"
                @click="onClickRegionParent(regionParent)"
              >
                {{regionParent.parentName}}
              </ElButton>
            </div>
          </div>
        </div>
        <div v-else class="region-children">
          <div class="header" @click="onClickBack">
            <ElIcon class="icon-back"><IconArrowLeft /></ElIcon>
            <span>{{selectingRegionParent.parentName}}</span>
          </div>
          <ElButton
            v-for="region in selectingRegionParent.platforms"
            :key="region.zoneName"
            text
            color="#353f58"
            class="region"
            @click="onClickRegion(region)"
          >
            {{region.zoneName}}
          </ElButton>
        </div>
      </div>
    </template>
  </ElDropdown>
</template>

<i18n lang="yaml" locale="zh-CN">
  regionSwitching: '资源池切换中'
</i18n>

<style lang="scss" scoped>
.region-selector {
  .selected-region {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 160px;
    height: 30px;
    font-size: 12px;
    color: #c2c2c2;
    background: #353f58;
    border-radius: 15px;

    &.active {
      color: #fff;
    }

    .content {
      display: flex;
      flex-direction: row;
      align-items: center;
    }

    .icon-location {
      width: 11px;
      height: 14px;
      margin: 0 10px 0 15px;
    }

    .icon-arrow {
      width: 8px;
      height: 4px;
      margin: 0 10px 0 15px;
      color: #929292;
      transition: color 1s transform 1s;

      &.down {
        color: #fff;
        transform: rotate(180deg);
      }
    }
  }
}

.regions-container {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 489px;
  padding: 20px 30px;
  font-size: 12px;
  color: #c2c2c2;
  background-color: #353f58;
  border-radius: 3px;

  .region-parent,
  .region {
    width: 100px;
    height: 28px;
    margin: 0;
    font-size: 12px;
    color: #c2c2c2;

    &.is-text:not(.is-disabled):hover {
      color: #fff;
      background-color: #272b39;
    }
  }
}

.region-groups {
  display: flex;
  flex-direction: column;

  .pinyin-row {
    display: flex;
    flex-direction: row;
  }

  .pinyin-range {
    flex-shrink: 0;
    width: 28px;
    height: 28px;
    line-height: 28px;
  }
}

.region-children {
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 18px;
    cursor: pointer;

    &:hover {
      color: #fff;
    }

    .icon-back {
      width: 7px;
      height: 12px;
      margin-right: 10px;
    }
  }
}
</style>

<style lang="scss">
.cns-main-app-el-dropdown__popper.cns-main-app-el-popper.region-popper {
  border: none;
  border-radius: 3px;

  .cns-main-app-el-popper__arrow::before {
    display: none;
  }
}
</style>
